package com.jt.yygh.hospital.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.jt.yygh.hospital.entity.hosp.Schedule;
import com.jt.yygh.hospital.repository.ScheduleRepository;
import com.jt.yygh.hospital.service.ScheduleService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.*;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.Map;

/**
 * @author jiang tao
 * @date 2022/3/3
 * @description:
 **/
@Service
public class ScheduleServiceImpl implements ScheduleService {
    @Autowired
    private ScheduleRepository scheduleRepository;

    @Override
    public void save(Map<String, Object> paramMap) {
        Schedule schedule = JSONObject.parseObject(JSONObject.toJSONString(paramMap), Schedule.class);

        Schedule targetSchedule = scheduleRepository.getScheduleByHosScheduleId(schedule.getHoscode(), schedule.getHosScheduleId());
        if(targetSchedule != null){
            BeanUtils.copyProperties(schedule, targetSchedule);
            scheduleRepository.save(targetSchedule);
        }else{
            schedule.setCreateTime(new Date());
            schedule.setUpdateTime(new Date());
            schedule.setIsDeleted(0);
            scheduleRepository.save(schedule);
        }
    }


    @Override
    public Page<Schedule> getSchedulePage(Map<String, Object> scheduleQuery) {
        Sort sort = Sort.by(Sort.Direction.DESC, "createTime");
        Pageable pageable = PageRequest.of((int)scheduleQuery.get("page")-1, (int) scheduleQuery.get("limit"), sort);

        Schedule schedule = new Schedule();
        schedule.setHoscode((String) scheduleQuery.get("hoscode"));
        schedule.setDepcode((String) scheduleQuery.get("depcode"));
        schedule.setIsDeleted(0);

        //创建匹配器 构建对象
        ExampleMatcher matcher = ExampleMatcher.matching()
            //改变默认字符串匹配方式；模糊查询
                .withStringMatcher(ExampleMatcher.StringMatcher.CONTAINING)
                //改变默认大小写忽略方式，忽略大小写
                .withIgnoreCase(true);
        // 创建实例
        Example<Schedule> example = Example.of(schedule, matcher);
        Page<Schedule> schedulePage = scheduleRepository.findAll(example, pageable);
        return schedulePage;
    }

    @Override
    public void remove(String hoscode, String hosScheduleId) {
        Schedule schedule = scheduleRepository.getScheduleByHoscodeAndHosScheduleId(hoscode, hosScheduleId);
        if(null != schedule) {
            scheduleRepository.deleteById(schedule.getId());
        }

    }
}
